package com.rosh.rpc.server.boot;

import com.rosh.rpc.core.netty.codec.FrameDecoder;
import com.rosh.rpc.core.netty.codec.FrameEncoder;
import com.rosh.rpc.core.netty.codec.RpcRequestDecoder;
import com.rosh.rpc.core.netty.codec.RpcResponseEncoder;
import com.rosh.rpc.core.netty.handler.RpcRequestHandler;
import com.rosh.rpc.server.config.RpcServerConfiguration;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: rosh
 * @Date: 2022/6/12 21:36
 */
@Component
@Slf4j
public class NettyServer {


    @Autowired
    private RpcServerConfiguration rpcServerConfiguration;

    /**
     * netty 启动
     */
    public void start() {

        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        DefaultEventLoopGroup business = new DefaultEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            //编码器
                            pipeline.addLast("frameEncoder", new FrameEncoder());
                            pipeline.addLast("rpcResponseEncoder", new RpcResponseEncoder());

                            //解码器
                            pipeline.addLast("frameDecoder", new FrameDecoder());
                            pipeline.addLast("rpcRequestDecoder", new RpcRequestDecoder());

                            //server handler
                            pipeline.addLast(business, "rpcRequestHandler", new RpcRequestHandler());
                        }
                    });

            serverBootstrap.bind(rpcServerConfiguration.getRpcPort()).sync();
            log.info("NettyServer 服务端已经启动.......");
        } catch (Exception e) {
            log.info("NettyServer invoke start failed. ", e);
            e.printStackTrace();
        }

    }


}
